package cn.yours.web.service.impl;


import cn.yours.web.constant.Constant;
import cn.yours.web.exception.AccountLockedException;
import cn.yours.web.exception.AccountNotFoundException;
import cn.yours.web.exception.AdminExistException;
import cn.yours.web.exception.PasswordErrorException;
import cn.yours.web.mapper.AdminMapper;
import cn.yours.web.pojo.dto.AdminDTO;
import cn.yours.web.pojo.entity.Admin;
import cn.yours.web.properties.JwtProperties;
import cn.yours.web.result.PageResult;
import cn.yours.web.service.IAdminService;
import cn.yours.web.util.JwtUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-06-05
 */
@Service
@Slf4j
public class AdminServiceImpl implements IAdminService
{
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 查询管理员
     * 
     * @param id 管理员主键
     * @return 管理员
     */
    @Override
    public Admin selectAdminById(Long id)
    {
        return adminMapper.selectAdminById(id);
    }

    /**
     * 查询管理员列表
     * 
     * @param
     * @return 管理员
     */
    @Override
    public PageResult selectAdminList(AdminDTO adminDTO)
    {
        PageHelper.startPage(adminDTO.getPageNo(),adminDTO.getPageSize());
        Page<Admin> pageList = adminMapper.selectAdminList(adminDTO);
        System.out.println(pageList);
        PageResult pageResult = new PageResult(pageList.getTotal(),pageList.getResult());
        return pageResult;
    }

    /**
     * 新增管理员
     * 
     * @param admin 管理员
     * @return 结果
     */
    @Override
    public int insertAdmin(Admin admin)
    {
        Admin adminByUsername = adminMapper.getAdminByUsername(admin.getUsername());
        if (adminByUsername!=null){
            throw new AdminExistException("管理员已经存在");
        }
        admin.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        return adminMapper.insertAdmin(admin);
    }

    /**
     * 修改管理员
     * 
     * @param admin 管理员
     * @return 结果
     */
    @Override
    public int updateAdmin(Admin admin)
    {
//        admin.setId(BaseContext.getCurrentId());
        if (admin.getPassword() != null){
            admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
        }
        return adminMapper.updateAdmin(admin);
    }

    /**
     * 批量删除管理员
     * 
     * @param ids 需要删除的管理员主键
     * @return 结果
     */
    @Override
    public int deleteAdminByIds(Long[] ids)
    {
        return adminMapper.deleteAdminByIds(ids);
    }

    /**
     * 删除管理员信息
     * 
     * @param id 管理员主键
     * @return 结果
     */
    @Override
    public int deleteAdminById(Long id)
    {
        return adminMapper.deleteAdminById(id);
    }
    /**
     * 注册用户
     * @param adminDTO
     * @return
     */
    @Override
    public int enroll(AdminDTO adminDTO) {
        //用户名已经存在了，不能注册
        if(adminMapper.getAdminByUsername(adminDTO.getUsername()) != null){
            throw new AdminExistException(Constant.ACCOUNT_NOT_EXIST);
        }
        // 密码加密
        String pwdLock = DigestUtils.md5DigestAsHex(adminDTO.getPassword().getBytes());
        adminDTO.setPassword(pwdLock);
        //属性拷贝
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminDTO,admin);
        int i = adminMapper.insertAdmin(admin);
        return i;
    }
    @Override
    public boolean forget(AdminDTO adminDTO) {
        Admin admin = adminMapper.getAdminByUsernameAndIdCard(adminDTO);
        if (admin==null){
            throw new AccountNotFoundException(Constant.ACCOUNT_NOT_EXIST);
        }
        String addSecret = DigestUtils.md5DigestAsHex("123456".getBytes());
        admin.setPassword(addSecret);
        log.info("{}",admin.getPassword());
        //重置管理员的密码
        adminMapper.updateAdmin(admin);
        return true;
    }

    @Override
    public void updatePwd(AdminDTO adminDTO) {
        //判断原来的密码是否正确
        Admin adminByUsername = adminMapper.getAdminByUsername(adminDTO.getUsername());
        if (!adminByUsername.getPassword().equals(DigestUtils.md5DigestAsHex(adminDTO.getPassword().getBytes())) ){
            throw new PasswordErrorException("密码错误,请输入正确密码");
        }
        adminDTO.setPassword(DigestUtils.md5DigestAsHex(adminDTO.getPassword().getBytes()));
        adminMapper.updatePwd(adminDTO);
    }

    @Override
    public String login(AdminDTO adminDTO) {
        //根据用户名查询用户
        Admin admin = adminMapper.getAdminByUsername(adminDTO.getUsername());
        if (admin == null){
            throw new AccountNotFoundException(Constant.ACCOUNT_NOT_EXIST);
        }
        //判断用户是否启用状态
        if (admin.getStatus() == 1){
            throw new AccountLockedException("账户被锁定，无法登录");
        }
        // 比对密码
        if (DigestUtils.md5DigestAsHex(adminDTO.getPassword().getBytes()).equals(admin.getPassword())){
            //创建jwt令牌
            Map<String,Object> claims = new HashMap<>();
            claims.put(Constant.ADMIN_ID,admin.getId());
            claims.put("username",admin.getUsername());
            String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
            return token;
        }
        throw new PasswordErrorException("用户密码错误");
    }
}
